package sample.one.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import sample.one.model.Foo;
import sample.one.model.Shop;
import sample.one.service.FooService;
import sample.one.service.ShopService;

public class DefaultFooService implements FooService {
	private JdbcTemplate jdbcTemplate; 
	private ShopService shopService;
	
	public DefaultFooService(){
		  
	}

	public Foo getFoo(String fooName) {
		Foo foo = (Foo) this.jdbcTemplate.queryForObject(
			    "select id, name from foo where name = ?",
			    new Object[]{new String(fooName)},
			    new RowMapper() {
			        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			        	Foo foo = new Foo();
			        	foo.setId(rs.getInt("id"));
			        	foo.setName(rs.getString("name"));
			            return foo;
			        }
			    });
		
		return foo;
	}

	public Foo getFoo(int id) {
		Foo foo = (Foo) this.jdbcTemplate.queryForObject(
			    "select id, name from foo where id = ?",
			    new Object[]{new Integer(id)},
			    new RowMapper() {
			        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			        	Foo foo = new Foo();
			        	foo.setId(rs.getInt("id"));
			        	foo.setName(rs.getString("name"));
			            return foo;
			        }
			    });
		
		return foo;
	}

	public void insertFoo(Foo foo) {
		Shop shop = new Shop();
		shop.setName("shop");
		shopService.insertShop(shop);
		this.jdbcTemplate.update(
		        "insert into foo (id,name) values (?,?)", 
		        new Object[] {new Integer(foo.getId()),foo.getName()});
//		this.jdbcTemplate.update(
//		        "insert into foo (id,name) values (?,?)", 
//		        new Object[] {new Integer(foo.getId()),foo.getName()});
	}

	public void updateFoo(Foo foo) {
		throw new UnsupportedOperationException();
	}
	
    
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

	@Override
	public void clear() {
		this.jdbcTemplate.update("delete from foo;");
	}

	public ShopService getShopService() {
		return shopService;
	}

	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}
	
	
}
